<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

// import { register } from 'node:module';
import { computed, h, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useVbenForm, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { Input, message } from 'ant-design-vue';

import { register } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Register' });

const router = useRouter();
const authStore = useAuthStore();

function goToLogin() {
  router.push('/auth/login');
}

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      renderComponentContent() {
        return {
          strengthText: () => $t('authentication.passwordStrength'),
        };
      },
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.confirmPassword'),
      },
      dependencies: {
        rules(values) {
          const { password } = values;
          return z
            .string({ required_error: $t('authentication.passwordTip') })
            .min(1, { message: $t('authentication.passwordTip') })
            .refine((value) => value === password, {
              message: $t('authentication.confirmPasswordTip'),
            });
        },
        triggerFields: ['password'],
      },
      fieldName: 'confirmPassword',
      label: $t('authentication.confirmPassword'),
    },
    {
      component: 'VbenInput',
      componentProps: {
        class: 'w-full',
        placeholder: $t('authentication.verificationCode'),
      },
      fieldName: 'code',
      label: $t('authentication.verificationCode'),
      rules: z
        .string()
        .min(1, { message: $t('authentication.verificationCodeTip') }),
    },
    {
      component: 'VbenInput',
      fieldName: 'uuid',
      componentProps: {
        class: 'hidden',
      },
    },
    {
      component: 'VbenCheckbox',
      fieldName: 'agreePolicy',
      renderComponentContent: () => ({
        default: () =>
          h('span', [
            $t('authentication.agree'),
            h(
              'a',
              {
                class: 'vben-link ml-1 ',
                href: '',
              },
              `${$t('authentication.privacyPolicy')} & ${$t('authentication.terms')}`,
            ),
          ]),
      }),
      rules: z.boolean().refine((value) => !!value, {
        message: $t('authentication.agreeTip'),
      }),
    },
  ];
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    hideLabel: true,
    hideRequiredMark: true,
  },
  handleSubmit,
  schema: formSchema.value,
  submitButtonOptions: {
    class: 'w-full',
  },
  resetButtonOptions: {
    class: 'hidden',
  },
  submitOnEnter: true,
});

async function handleSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    const {
      data: { code, msg },
    } = await register(values);
    if (code === 200) {
      message.success('注册成功！');
      goToLogin();
    } else {
      message.error(msg);
    }
  } else {
    message.error('意外的错误！');
  }
}

onMounted(() => {
  authStore.getCaptcha();
  watch(
    () => authStore.captcha.uuid,
    (newUuid) => {
      if (newUuid) {
        formApi.setFieldValue('uuid', newUuid);
      }
    },
  );
});
</script>

<template>
  <Form>
    <template #code="slotProps">
      <Input
        class="mr-2 h-10"
        v-bind="slotProps"
        @input="slotProps['onUpdate:modelValue']($event.target.value)"
      />
      <img
        :src="authStore.captcha.img"
        alt=""
        @click="authStore.getCaptcha"
        class="h-10"
      />
    </template>
  </Form>
  <div class="mt-4 text-center text-sm">
    {{ $t('authentication.alreadyHaveAccount') }}
    <span class="vben-link text-sm font-normal" @click="goToLogin">
      {{ $t('authentication.goToLogin') }}
    </span>
  </div>
</template>
<style lang="scss" scoped>
:deep(.col-span-full .w-full .text-right .pb-6) {
  display: flex;
}
</style>
